<?php

namespace app\sys\model;

use app\admin\model\Duty;
use app\admin\model\Staff;
use app\common\CommandCron;
use think\Db;
use think\Exception;
use \think\Model;

class Team extends Model
{
    protected $autoWriteTimestamp = true;
    /**
     * 列表(list)
     * @param $search
     * @param $page
     * @param $limit
     * @return array
     */
    public static function ModelList($search,$page, $limit): array
    {
        $userSql = Team::field("id,name,
        month,month_day,
        next_month,next_month_day,week,
        staff_num");
        if ($search) {
            $userSql = $userSql->where('name', "like", "%" . $search . "%");
        }
        $count = $userSql->count();
        $list = $userSql->page($page, $limit)->order('id', 'asc')->select();

        foreach($list as $k => $v){
//            // 判断是否是当前月
//            if($v["month"] != strtotime(date("Y-m-d"))){
//                $list[$k]["month"] = 0;
//                $list[$k]["month_day"] = "";
//            }
//
//            // 判断下个月
//            if($v["net_month"] == strtotime(date("Y-m-d"))){
//                $list[$k]["net_month"] = $v["month"];
//                $list[$k]["net_month_day"] = $v["month_day"];
//            }else{
//                $list[$k]["net_month"] = 0;
//                $list[$k]["net_month_day"] = "";
//            }


            $m = TeamTime::where("team_id",$v["id"])->where("type","new")->column("day");
            $monAll = [];
            foreach ($m as $k1 => $v2){
               $monAll[] = date("Y-m-d",$v2);
            }
            $list[$k]["month"] = $monAll;

            $m2 = TeamTime::where("team_id",$v["id"])->where("type","next")->column("day");
            $nmonAll = [];
            foreach ($m2 as $k1 => $v2){
                $nmonAll[] = date("Y-m-d",$v2);
            }
            $list[$k]["next_month"] = $nmonAll;

            $m = TeamTime::where("team_id",$v["id"])->where("type","other")->column("day");
            $oAll = [];
            foreach ($m as $k1 => $v2){
                $oAll[] = date("Y-m-d",$v2);
            }
            $list[$k]["other"] = $oAll;

            $a = explode(",",$list[$k]["week"]);
            $a = $a == [""]?[]:$a;
            $list[$k]["week"] = $a;

        }

        return listDate($list, $count);
    }

    /**
     * 添加(add)
     * @param $data
     * @return string
     * @throws \Exception
     */
    public static function ModelAdd($data): string
    {
        Db::startTrans();
        try {
            if(isset($data["name"]) && $data["name"]){
                $userInfo = Team::where("name", $data["name"])->find();
                if ($userInfo) {
                    return "小组已存在~";
                }
                $dataT["name"] = $data["name"];
            }

            if(isset($data["month"]) && $data["month"]){
                $dataT["month"] = GetMonBy($data["month"]);
                $dataT["month_day"] = GetDayBy($data["month"]);
            }

            if(isset($data["next_month"]) && $data["next_month"])
            {
                $dataT["next_month"] = GetMonBy($data["next_month"]);
                $dataT["next_month_day"] = GetDayBy($data["next_month"]);
            }

            if(isset($data["week"]) && $data["week"])
            {
                foreach ($data["week"] as $k => $v){
                    if (!in_array($v,[6,7])){
                        return "只能设置星期六或星期天";
                    }
                }
                $dataT["week"] =  implode(",",$data["week"]);
            }

            if(isset($data["other_day"]) && $data["other_day"])
            {
                $dataT["other_day"] = GetDayBy($data["other_day"]);
            }
            if(empty($dataT))return "数据不能为空~";

            $t = Team::create($dataT);
            TeamTime::ModelAdd($t["id"], $data["month"], $data["next_month"],$data["other_day"],$data["week"]);
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return "添加异常~";
        }
        return "";
    }

    /**
     * 修改（update）
     * @param $id
     * @param $data
     * @return string
     * @throws \Exception
     */
    public static function ModelUp($id, $data): string
    {
        Db::startTrans();
        try {
            if(isset($data["name"]) && $data["name"]){
                $userInfo = Team::where("name", $data["name"])->find();
                if (!$userInfo) {
                    return "小组已不存在~";
                }
                $dataT["name"] = $data["name"];
            }

            if(isset($data["month"]) && $data["month"]){
                $dataT["month"] = GetMonBy($data["month"]);
                $dataT["month_day"] = GetDayBy($data["month"]);
            }

            if(isset($data["next_month"]) && $data["next_month"])
            {
                $dataT["next_month"] = GetMonBy($data["next_month"]);
                $dataT["next_month_day"] = GetDayBy($data["next_month"]);
            }

            if(isset($data["week"]) && $data["week"])
            {
                foreach ($data["week"] as $k => $v){
                    if (!in_array($v,[6,7])){
                        return "只能设置星期六或星期天";
                    }
                }
                $dataT["week"] =  implode(",",$data["week"]);
            }

            if(isset($data["other_day"]) && $data["other_day"])
            {
                $dataT["other_day"] = GetDayBy($data["other_day"]);
            }

            if(empty($dataT))return "数据不能为空~";
            $resUp = Team::where("id", $id)->data($dataT)->update();
            if (!$resUp) {
                Db::rollback();
                return "修改失败~";
            }
            TeamTime::ModelAdd($id, $data["month"], $data["next_month"],$data["other_day"],$data["week"]);
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return "";
    }

    /**
     * 删除（delete）
     * @param array $id
     * @return string
     * @throws Exception
     */
    public static function ModelDel($id = []): string
    {
        $userInfo = Team::where("id", "in", $id)->find();
        if (!$userInfo) {
            return "数据不存在~";
        }
        Db::startTrans();
        try {
            $resUp = Team::where("id", "in", $id)->delete();
            if (!$resUp) {
                Db::rollback();
                return "删除失败~";
            }
            $res = TeamTime::ModelDel($id);
            if($res){
                Db::rollback();
                return $res;
            }
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return "删除异常~";
        }
        return "";
    }

    /**
     * 详情（detail）
     * @param $id
     * @return Model
     */
    public static function ModelDet($id): Model
    {
        return Team::where("id", $id)->find();
    }

    /**
     *  分组设置列表
     */
    public static function TeamSetList()
    {
        return Team::field("id,name")->order('id', 'asc')->select();
    }

    /**
     *  分组设置列表add
     * @param array $staffId
     * @param int $teamId
     * @return string
     */
    public static function TeamSet($staffId = [],$teamId = 0):string
    {
        Db::startTrans();
        try {
            foreach ($staffId as $k => $v){
                Staff::where("id",$v)->data(["team_id"=>$teamId])->update();
            }

            $sCount = Staff::where("team_id",$teamId)->count();
            $staffNum = $sCount;
            Team::where("id",$teamId)->data(["staff_num"=>$staffNum])->update();

            $staffNos = Staff::where("id","in",$staffId)->column("staff_no");
            // redis列表修改
            Staff::NewAllocStaffList($staffNos,"af");
            // 修改状态
            CommandCron::autoUpStaffStatus();
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return "添加异常";
        }
        return "";
    }
}